package tk.mybatis.springboot.spider.utils;

/**
 * Created with IntelliJ IDEA.
 * User: LinZhaoguan
 * Date: 2016/12/9
 * Time: 16:06
 * Email:linzhaoguan@astroway.net
 */


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * httpclient访问http接口的工具类
 *
 * @author minux
 */
public class HttpClientUtils {

    // 接口地址
    private static String apiURL = "";
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
    private HttpClient httpClient = null;
    private HttpPost httpPost = null;
    private HttpGet httpGet = null;
    private long startTime = 0L;
    private long endTime = 0L;
    private int status = 0;

    public HttpClientUtils() {

    }

    /**
     * 接口地址
     *
     * @param url
     */
    public HttpClientUtils(String url) {

        if (url != null) {
            this.apiURL = url;
        }
        if (apiURL != null) {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(apiURL);
        }
    }

    /**
     * 调用 API
     *
     * @param parameters
     * @return
     */
    public String post(String parameters) {
        String body = null;
        logger.info("parameters:" + parameters);

        if (httpPost != null & parameters != null
                && !"".equals(parameters.trim())) {
            try {
                // 建立一个NameValuePair数组，用于存储欲传送的参数
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
                startTime = System.currentTimeMillis();

                HttpResponse response = httpClient.execute(httpPost);

                endTime = System.currentTimeMillis();
                int statusCode = response.getStatusLine().getStatusCode();

                logger.info("statusCode:" + statusCode);
                logger.info("POST API 花费时间(单位：毫秒)：" + (endTime - startTime));
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("Method failed:" + response.getStatusLine());
                    status = 1;
                }

                // Read the response body
                body = EntityUtils.toString(response.getEntity());

            } catch (IOException e) {
                // 网络错误
                status = 3;
            } finally {
                logger.info("调用接口状态：" + status);
                httpPost.releaseConnection();
            }

        }
        return body;
    }

    /**
     * 通过httpclient到指定的uri来get数据
     */
    public String getData() {
        String body = null;
        httpGet = new HttpGet(apiURL);
        try {
            startTime = System.currentTimeMillis();
            HttpResponse httpResponse = httpClient.execute(httpGet);
            endTime = System.currentTimeMillis();

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            logger.info("statusCode:" + statusCode);
            logger.info("GET  API 花费时间(单位：毫秒)：" + (endTime - startTime));
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed:" + httpResponse.getStatusLine());
                status = 1;
            }
            // Read the response body
            body = EntityUtils.toString(httpResponse.getEntity());
        } catch (IOException e) {
            // 网络错误
            status = 3;
        } finally {
            logger.info("调用接口状态：" + status);
            httpGet.releaseConnection();
        }
        return body;
    }

    /**
     * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
     *
     * @return the status
     */
    public int getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(int status) {
        this.status = status;
    }

    /**
     * @return the startTime
     */
    public long getStartTime() {
        return startTime;
    }

//    /**
//     * 设置代理
//     */
//    public static String useProxy(String url) {
//        // 首先获取实例类
//        CrawlUtil crawler = CrawlUtil.getInstance();
//
//        // 设置订单号，这里替换成您自己的订单号
//        crawler.setOrder("979f8e76d9fbf3c61462b662cb7823dd");
//
//        // 设置请求超时时间，单位为毫秒，默认为5秒
//        crawler.setConnectTimeOut(15000);
//
//        // 开启调试模式，开启状态下将会在console控制台输出执行信息
//        crawler.setDebug(true);
//
//        // 代理IP会失效，这个参数设置最大的失效次数。如果超过这个数字，将直接请求网址（不使用代理）
//        crawler.setMaxTryTime(5);
//
//        // Header请求头中添加随机的referer信息
//        crawler.setRandomReferer(true);
//
//        // Header请求头中添加随机的User-Agent信息
//        crawler.setRandomUserAgent(true);
//
//        // 动态代理用户请设置为true，普通代理请设置为false
//        crawler.setDynamic(false);
//        try {
//            // 请求百度的HTML源码，第二个参数true表示使用代理IP
//            String data = crawler.proxyGetFromUrl(url, 5, true, "UTF-8");
//            System.out.println("data===="+data);
//            return data;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//
//    }

//    public static void main(String[] args) {
//        useProxy("http://api.goubanjia.com/api/get.shtml?order=979f8e76d9fbf3c61462b662cb7823dd&num=100&carrier=0&protocol=0&an1=1&an2=2&an3=3&sp1=1&sp2=2&sp3=3&sort=1&system=1&distinct=0&rettype=0&seprator=%0D%0A");
//    }

}